import axios from "axios";
import {ElMessage} from "element-plus";
const auth_name = "access_token"
const defaultFailure = (url,message,code) => {
  console.log(
      `请求失败，请检查网络，或者联系管理员，错误信息：${message}，错误码：${code}，请求地址：${url}`
  );
    ElMessage.warning(message);
};
const defaultError = (error) => {
    console.error(
        error
    );
    ElMessage.error("出现错误");
};
function getToken() {
    const str = localStorage.getItem(auth_name) || sessionStorage.getItem(auth_name);
    if(!str) return null;
    const authObj = JSON.parse(str);
    if(str.expires < new Date().getTime()){
        deleteToken();
        return null;
    }else{
        return authObj.token;
    }
}
function storeToken(token,remeber,expire) {
    const authObj = {token: token,expire: expire}
    if(remeber){
        sessionStorage.setItem(auth_name,JSON.stringify(authObj));
    }else{
        localStorage.setItem(auth_name,JSON.stringify(authObj));
    }

}
function deleteToken() {
    localStorage.removeItem(auth_name);
    sessionStorage.removeItem(auth_name);
}
function accessHeader() {
    const token = getToken();
    if(!token) return null;
    return {
      Authorization: `Bearer ${token}`,
  }
}

function internalPost(url, data,header,success,failure,error=defaultError) {
  return axios.post(url, data, {
    headers: header,
  }).then(({data}) =>{
      if(data.code === 200){
          success(data.data);

      }else {
          failure(url,data.message,data.code);

      }}

  ).catch(err => error(err));
}
function internalGet(url,header,success,failure,error=defaultError) {
    return axios.get(url, {
        headers: header,
    }).then(({data}) =>{
        if(data.code === 200){
            success(data.data);

        }else {
            failure(url,data.message,data.code);

        }}

    ).catch(err => error(err));
}
function get(url,success,failure = defaultFailure){

    internalGet(url, accessHeader(),success,failure)
}
function post(url,data,success,failure = defaultFailure){
    internalPost(url,data, accessHeader(),success,failure)
}
function login(username, password, remember, success, failure = defaultFailure) {
    if (typeof defaultFailure !== 'function') {
        throw new Error('defaultFailure must be a function');
    }

    internalPost("/api/auth/login",
        {
            username: username,
            password: password,
        },
        {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        (data) => {
            ElMessage.success(`登录成功，欢迎${data.name}来到我们的系统`);
            storeToken(data.token,remember,data.expire);
            success(data);
        },
        failure
    );
}
function logout(success,failure=defaultFailure){

    get("/api/auth/logout",()=>{
        ElMessage.success("退出成功，欢迎下次使用")
        deleteToken();
        success()
    },failure)
}
function isUnAuhtorized(){
    return !getToken();
}
export {login,post,get,logout,isUnAuhtorized,accessHeader}
